package Server;

import java.net.*;
import java.util.concurrent.AbstractExecutorService;
import java.io.*;

import DAO.Util.AESUtil;

public class TCPServer {
	public static void main(String args[]) {
		try {
			int serverPort = 7896; // the server port
			ServerSocket listenSocket = new ServerSocket(serverPort);
			while (true) {
				Socket clientSocket = listenSocket.accept();
				Connection c = new Connection(clientSocket);
			}
		} catch (IOException e) {
			System.out.println("Listen socket:" + e.getMessage());
		}
	}
}

class Connection extends Thread {
	private DataInputStream in;
	private DataOutputStream out;
	private Socket clientSocket;

	Despachante desp = new Despachante();

	public Connection(Socket aClientSocket) {
		conexao(aClientSocket);
	}

	public void sendResponse(String response) {
		try {
			System.out.println("Enviado decriptografado: "+response);
			byte[] data = AESUtil.encriptografar(response);
			System.out.println("Enviado criptografado: "+new String(data));
			out.writeInt(data.length);
			out.write(data);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

		
	public String getResquest() {
		try {
			int tamanho = in.readInt();
			byte[] fromClient = new byte[tamanho];
            in.read(fromClient, 0, fromClient.length);
            System.out.println("Recebido criptografado: "+new String(fromClient));
			String data = AESUtil.decriptografar(fromClient);
			System.out.println("Recebido decriptografado: "+data);
			return data;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}

	public void run() {
		try {
			String data = getResquest();
			data = desp.invoke(data);
			sendResponse(data);
		} finally {
			try {
				clientSocket.close();
			} catch (IOException e) {
			}
		}
	}

	private void conexao(Socket aClientSocket){
		try {
			clientSocket = aClientSocket;
			in = new DataInputStream(clientSocket.getInputStream());
			out = new DataOutputStream(clientSocket.getOutputStream());
			this.start();
		} catch (IOException e) {
			System.out.println("Connection:" + e.getMessage());
		}
	}
}